#include <cstdint>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <chrono>
#include <thread>
#include <utility>
#include <cmath>
#include <limits>
#include <map>
#include <queue>
#include <numeric>

// Windows 专用头文件
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <winsock2.h>   
#include <ws2tcpip.h>
#endif

// 第三方库头文件
#include <curl/curl.h>
#include "crow_all.h"
#include "curl_wrapper/curl_wrapper.h"
#include "nlohmann/json.hpp"
#include <sqlite3.h>

// 项目专用头文件
#include "map_service.h"
#include "models/place_extensions.h"

// CURL_STATICLIB 定义
#if defined(_WIN32) && !defined(CURL_STATICLIB)
// #define CURL_STATICLIB // 如果libcurl是静态库且有链接错误时取消注释
#endif

// 全局静态变量，存储用于第一个构造函数的应用实例
static crow::SimpleApp defaultApp;

// 全局CURL初始化和清理
class CurlGlobalManager {
public:
    CurlGlobalManager() {
        curl_global_init(CURL_GLOBAL_ALL);
        std::cout << "CURL global initialization complete" << std::endl;
    }

    ~CurlGlobalManager() {
        curl_global_cleanup();
        std::cout << "CURL global cleanup complete" << std::endl;
    }
};

// 创建全局单例对象以确保CURL在程序启动时初始化并在结束时清理
static CurlGlobalManager curlManager;

// CURL响应回调函数
size_t MapService::WriteCallback(void* contents, size_t size, size_t nmemb, void* userp) {
    return curl_wrapper::writeCallback(contents, size, nmemb, userp);
}

// 辅助函数：读取文件内容
static std::string readFile(const std::string& filename) {
    std::ifstream file(filename);
    if (!file.is_open()) {
        return "";
    }

    std::stringstream buffer;
    buffer << file.rdbuf();
    return buffer.str();
}

// 纭繚璺緞鐩稿叧鐨勬暟鎹〃瀛樺湪
void MapService::ensurePathTablesExist() {
    std::cout << "确保路网相关表存在..." << std::endl;
    
    sqlite3* db;
    if (sqlite3_open(dbPath_.c_str(), &db) != SQLITE_OK) {
        std::cerr << "打开数据库失败: " << sqlite3_errmsg(db) << std::endl;
        return;
    }
    
    // 创建路径节点表
    const char* createNodeTableSQL = 
        "CREATE TABLE IF NOT EXISTS path_nodes ("
        "id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "name TEXT,"
        "type TEXT DEFAULT 'junction',"
        "longitude REAL NOT NULL,"
        "latitude REAL NOT NULL,"
        "place_id INTEGER DEFAULT 0"
        ");";
    
    // 创建路径表
    const char* createPathTableSQL = 
        "CREATE TABLE IF NOT EXISTS paths ("
        "id INTEGER PRIMARY KEY AUTOINCREMENT,"
        "name TEXT,"
        "start_node_id INTEGER NOT NULL,"
        "end_node_id INTEGER NOT NULL,"
        "distance REAL NOT NULL,"
        "walking_time INTEGER,"
        "riding_time INTEGER,"
        "allow_bike INTEGER DEFAULT 1,"
        "congestion_base REAL DEFAULT 0.7,"
        "geometry TEXT,"
        "path_level INTEGER DEFAULT 2,"
        "bidirectional INTEGER DEFAULT 1,"
        "FOREIGN KEY (start_node_id) REFERENCES path_nodes(id),"
        "FOREIGN KEY (end_node_id) REFERENCES path_nodes(id)"
        ");";
    
    char* errMsg = nullptr;
    if (sqlite3_exec(db, createNodeTableSQL, NULL, NULL, &errMsg) != SQLITE_OK) {
        std::cerr << "创建节点表失败: " << errMsg << std::endl;
        sqlite3_free(errMsg);
    }
    
    if (sqlite3_exec(db, createPathTableSQL, NULL, NULL, &errMsg) != SQLITE_OK) {
        std::cerr << "创建路径表失败: " << errMsg << std::endl;
        sqlite3_free(errMsg);
    }
    
    // 创建索引以提高查询性能
    const char* createIndexSQL = 
        "CREATE INDEX IF NOT EXISTS idx_path_nodes_location ON path_nodes(longitude, latitude);"
        "CREATE INDEX IF NOT EXISTS idx_paths_nodes ON paths(start_node_id, end_node_id);";
    
    if (sqlite3_exec(db, createIndexSQL, NULL, NULL, &errMsg) != SQLITE_OK) {
        std::cerr << "创建索引失败: " << errMsg << std::endl;
        sqlite3_free(errMsg);
    }
    
    sqlite3_close(db);
    std::cout << "路网表结构检查和创建完成" << std::endl;
}

// MapService鏋勯€犲嚱鏁? - 浣跨敤榛樿鍏ㄥ眬app
MapService::MapService(const std::string& apiKey) 
    : ak(apiKey), 
      app_(defaultApp), 
      dbPath_("tour_system.db") {
    // 注意：此构造函数使用默认应用实例
    // 调用者需要使用setupMapRoutes静态方法
    ensurePathTablesExist();
}

// 完整构造函数 - 提供app实例和数据库路径
MapService::MapService(crow::SimpleApp& app, const std::string& dbPath) 
    : app_(app), 
      dbPath_(dbPath) {
    // 服务端应用的API密钥数组（用于Web API调用）
    // 这些密钥支持：静态图、地点检索、路线规划、驾车路线规划（轻量）、
    // 骑行路线规划（轻量）、步行路线规划（轻量）、公交路线规划（轻量）、
    // 地理编码、逆地理编码等服务
    serverAks = {
        "J6djdBIbhZhNKa1P61VOUoNEpk2Kdevc",
        "YWYhzv8agmWHMH3YXoHBAJIIDQfiUAzY", 
        "edOGvVM3YdCq23nY7uNCNlbRGwBPvtxq",
        "DdWf4UMiBW1HURagyJqvqlcWA3oetCkK"
    };
    
    // 当前使用的服务端密钥索引
    currentServerAkIndex = 0;
    
    // 设置当前使用的密钥
    ak = serverAks[currentServerAkIndex];
    
    // 确保路网相关表存在
    ensurePathTablesExist();
}

// 获取地图页面HTML
crow::response MapService::getMapPage() {
    crow::response res;
    res.set_header("Content-Type", "text/html; charset=UTF-8");

    // 从文件读取HTML内容
    std::string html = readFile("html/map.html");

    // 如果文件读取失败，返回错误消息
    if (html.empty()) {
        html = "<html><body><h1>错误：无法加载地图页面</h1><p>请确保html/map.html文件存在且可读。</p></body></html>";
    }

    res.body = html;
    return res;
}

// 获取单个地点地图页面
crow::response MapService::getSinglePlaceMapPage() {
    // 创建响应对象
    crow::response res;
    res.set_header("Content-Type", "text/html; charset=UTF-8");
    
    // 读取北京大学地图HTML文件
    std::string html = readFile("html/pku_map.html");
    
    // 如果文件读取失败，返回错误消息
    if (html.empty()) {
        html = "<html><body><h1>错误：无法加载北大地图页面</h1><p>请确保html/pku_map.html文件存在且可读。</p></body></html>";
    }
    
    // 设置响应体
    res.body = html;
    return res;
}

// 将地点数据转换为JSON格式
crow::json::wvalue MapService::convertPlacesToJson(const std::vector<Place>& places) {
    crow::json::wvalue::list placesList;

    for (const auto& place : places) {
        crow::json::wvalue placeJson;
        placeJson["id"] = place.id;
        placeJson["name"] = place.name;
        placeJson["type"] = place.type;
        placeJson["latitude"] = place.latitude;
        placeJson["longitude"] = place.longitude;
        placeJson["description"] = place.description;
        placeJson["outline"] = place.outline;
        placeJson["address"] = place.address;
        placeJson["popularity"] = place.popularity;
        placeJson["rating"] = place.rating;

        placesList.push_back(std::move(placeJson));
    }

    return crow::json::wvalue(std::move(placesList));
}

/**
 * 设置地图相关路由
 * @param app Crow应用实例
 * @param mapService 地图服务实例
 * @param placeDb 地点数据库实例
 */
void MapService::setupMapRoutes(crow::SimpleApp& app, MapService& mapService, PlaceDB& placeDb) {
    // 地图页面路由已在main.cpp中设置
    
    // 单个地点地图页面路由
    CROW_ROUTE(app, "/place/<int>")
    ([&mapService, &placeDb](int id) {
        std::cout << "单个地点地图页面请求，地点ID: " << id << std::endl;
        
        // 检查ID是否有效
        Place place = placeDb.getPlaceById(id);
        if (place.id == 0) {
            std::cout << "警告: 找不到ID为 " << id << " 的地点，默认使用北大地图。" << std::endl;
        } else {
            std::cout << "找到地点: " << place.name << " (ID=" << place.id << ")" << std::endl;
            
            // 增加热度 - 无论是什么地点，只要被查看就增加热度
            double oldPopularity = place.popularity;
            double newPopularity = oldPopularity + 0.5;
            bool success = placeDb.updatePlacePopularity(id, newPopularity);
            
            if (success) {
                std::cout << "更新 " << place.name << " 的热度从 " << oldPopularity << " 到 " << newPopularity << std::endl;
            }
        }
        
        // 无论ID是什么，都返回北京大学地图页面 - 按照需求显示单点地图
        return mapService.getSinglePlaceMapPage();
    });

    // 单个地点地图测试路由，用于调试
    CROW_ROUTE(app, "/test_single_map/<int>")
    ([&placeDb](int id) {
        Place place = placeDb.getPlaceById(id);
        std::string html;
        
        html = "<!DOCTYPE html><html><head><title>单个地点地图测试</title></head><body>";
        html += "<h1>测试单个地点地图</h1>";
        html += "<p>地点ID: " + std::to_string(id) + "</p>";
        
        if (place.id > 0) {
            html += "<p>地点名称: " + place.name + "</p>";
            html += "<p>地点类型: " + place.type + "</p>";
            html += "<p>经度: " + std::to_string(place.longitude) + "</p>";
            html += "<p>纬度: " + std::to_string(place.latitude) + "</p>";
        } else {
            html += "<p>找不到地点</p>";
        }
        
        html += "<p><a href='/place/" + std::to_string(id) + "'>前往单个地点地图</a></p>";
        html += "</body></html>";
        
        crow::response res;
        res.set_header("Content-Type", "text/html; charset=UTF-8");
        res.body = html;
        return res;
    });

    // 增加地点热度API
    CROW_ROUTE(app, "/api/increase_popularity/<int>")
    .methods("POST"_method)
    ([&placeDb](const crow::request& req, int id) {
        std::cout << "收到增加热度请求，地点ID: " << id << std::endl;
        
        Place place = placeDb.getPlaceById(id);
        if (place.id == 0) {
            crow::json::wvalue error;
            error["error"] = "找不到地点";
            return crow::response(404, error);
        }
        
        double oldPopularity = place.popularity;
        double newPopularity = oldPopularity + 0.5;
        
        bool success = placeDb.updatePlacePopularity(id, newPopularity);
        
        crow::json::wvalue result;
        if (success) {
            result["success"] = true;
            result["old_popularity"] = oldPopularity;
            result["new_popularity"] = newPopularity;
        } else {
            result["success"] = false;
            result["error"] = "更新热度失败";
        }
        
        return crow::response(result);
    });

    // 获取所有地点API
    CROW_ROUTE(app, "/api/places")
    .methods("GET"_method)
    ([&mapService, &placeDb](){
        auto places = placeDb.getAllPlaces();
        return crow::response(mapService.convertPlacesToJson(places));
    });

    // 按类型获取地点API
    CROW_ROUTE(app, "/api/places/type/<string>")
    .methods("GET"_method)
    ([&mapService, &placeDb](const std::string& type){
        auto places = placeDb.getPlacesByType(type);
        return crow::response(mapService.convertPlacesToJson(places));
    });
    
    // Get place details API
    CROW_ROUTE(app, "/api/places/<int>")
    .methods("GET"_method)
    ([&mapService, &placeDb](int id){
        std::cout << "访问地点详情API，地点ID: " << id << std::endl;
        
        Place place = placeDb.getPlaceById(id);
        crow::json::wvalue placeJson;
        
        if (place.id > 0) {
            // 保存当前热度
            double originalPopularity = place.popularity;
            
            // 每次查看地点详情时增加热度
            double newPopularity = originalPopularity + 0.5;
            std::cout << "准备增加地点热度: ID=" << id << ", 原始热度=" << originalPopularity << ", 新热度=" << newPopularity << std::endl;
            
            bool success = placeDb.updatePlacePopularity(place.id, newPopularity);
            
            if (success) {
                // 更新成功，使用新的热度值
                std::cout << "地点热度更新成功，ID=" << id << ", 新热度=" << newPopularity << std::endl;
                place.popularity = newPopularity;
            } else {
                std::cerr << "地点热度更新失败，ID=" << id << std::endl;
            }
            
            // 构建JSON响应
            placeJson["id"] = place.id;
            placeJson["name"] = place.name;
            placeJson["type"] = place.type;
            placeJson["latitude"] = place.latitude;
            placeJson["longitude"] = place.longitude;
            placeJson["description"] = place.description;
            placeJson["outline"] = place.outline;
            placeJson["address"] = place.address;
            placeJson["popularity"] = place.popularity;  // 使用更新后的热度
            placeJson["rating"] = place.rating;
        } 
        else {
            placeJson["error"] = "找不到地点";
        }
        
        return crow::response(placeJson);
    });
    
    // 获取内部地点API
    CROW_ROUTE(app, "/api/places/<int>/internal")
    .methods("GET"_method)
    ([&mapService, &placeDb](int placeId){
        auto internalPlaces = placeDb.getInternalPlaces(placeId);
        
        crow::json::wvalue::list placesList;
        for (const auto& place : internalPlaces) {
            crow::json::wvalue placeJson;
            placeJson["id"] = place.id;
            placeJson["parent_id"] = place.parent_id;
            placeJson["name"] = place.name;
            placeJson["type"] = place.type;
            placeJson["latitude"] = place.latitude;
            placeJson["longitude"] = place.longitude;
            placeJson["description"] = place.description;
            
            placesList.push_back(std::move(placeJson));
        }
        
        return crow::response(crow::json::wvalue(std::move(placesList)));
    });
    
    // 搜索地点API
    CROW_ROUTE(app, "/api/places/search")
    .methods("GET"_method)
    ([&mapService, &placeDb](const crow::request& req){
        auto params = req.url_params;
        std::string keyword = params.get("keyword");
        std::string sortBy = params.get("sortBy") ? params.get("sortBy") : "relevance";
        
        if (keyword.empty()) {
            crow::json::wvalue error;
            error["error"] = "缺少搜索关键词";
            return crow::response(400, error);
        }
        
        std::vector<Place> places;
        if (sortBy == "popularity") {
            places = placeDb.searchPlacesByPopularity(keyword);
        } else if (sortBy == "rating") {
            places = placeDb.searchPlacesByRating(keyword);
        } else {
            // 默认按相关性排序
            places = placeDb.searchPlaces(keyword);
        }
        
        return crow::response(mapService.convertPlacesToJson(places));
    });
    
    // 获取推荐地点API（按热度）
    CROW_ROUTE(app, "/api/places/recommend/popularity")
    ([&mapService, &placeDb](const crow::request& req) {
        auto params = req.url_params;
        int limit = params.get("limit") ? std::stoi(params.get("limit")) : 10;
        
        auto places = placeDb.getRecommendedPlacesByPopularity(limit);
        return crow::response(mapService.convertPlacesToJson(places));
    });
    
    // 获取推荐地点API（按评分）
    CROW_ROUTE(app, "/api/places/recommend/rating")
    ([&mapService, &placeDb](const crow::request& req) {
        auto params = req.url_params;
        int limit = params.get("limit") ? std::stoi(params.get("limit")) : 10;
        
        auto places = placeDb.getRecommendedPlacesByRating(limit);
        return crow::response(mapService.convertPlacesToJson(places));
    });
    
    // 更新地点评分API
    CROW_ROUTE(app, "/api/places/<int>/rate")
    .methods("POST"_method)
    ([&placeDb](const crow::request& req, int placeId){
        auto x = crow::json::load(req.body);
        if (!x) {
            crow::json::wvalue error;
            error["error"] = "无效的JSON数据";
            return crow::response(400, error);
        }
        
        double rating = x["rating"].d();
        if (rating < 1 || rating > 5) {
            crow::json::wvalue error;
            error["error"] = "评分必须在1到5之间";
            return crow::response(400, error);
        }
        
        // 获取当前地点
        Place place = placeDb.getPlaceById(placeId);
        if (place.id == 0) {
            crow::json::wvalue error;
            error["error"] = "找不到地点";
            return crow::response(404, error);
        }
        
        // 更新地点评分
        double newRating = (place.rating == 0) ? rating : (place.rating * 0.8 + rating * 0.2);
        placeDb.updatePlaceRating(placeId, newRating);
        
        crow::json::wvalue result;
        result["success"] = true;
        result["new_rating"] = newRating;
        return crow::response(result);
    });
    
    // 添加路线规划代理API
    CROW_ROUTE(app, "/api/route")
    .methods("GET"_method)
    ([&mapService](const crow::request& req) {
        try {
            // Get coordinates and mode from request parameters
            double startLat = std::stod(req.url_params.get("startLat"));
            double startLng = std::stod(req.url_params.get("startLng"));
            double endLat = std::stod(req.url_params.get("endLat"));
            double endLng = std::stod(req.url_params.get("endLng"));
            std::string mode = req.url_params.get("mode") ? req.url_params.get("mode") : "driving";
            
            // Ensure mode is either driving or walking
            if (mode != "driving" && mode != "walking") {
                mode = "driving";
            }
            
            // 使用支持密钥轮换的方法
            return mapService.proxyRouteApiWithRetry(startLat, startLng, endLat, endLng, mode);
        } catch (const std::exception& e) {
            // Handle exception
            crow::json::wvalue result;
            result["status"] = 500;
            result["message"] = std::string("Error: ") + e.what();
            return crow::response(500, result);
        }
    });

    // 路网编辑器API - 获取所有路径节点
    CROW_ROUTE(app, "/api/path_nodes")
    .methods("GET"_method)
    ([&mapService]() {
        return mapService.getAllPathNodes();
    });
    
    // 路网编辑器API - 创建路径节点
    CROW_ROUTE(app, "/api/path_nodes")
    .methods("POST"_method)
    ([&mapService](const crow::request& req) {
        try {
            auto x = crow::json::load(req.body);
            if (!x) {
                crow::json::wvalue error;
                error["error"] = "无效的JSON数据";
                return crow::response(400, error);
            }
            
            std::string name = x.has("name") ? x["name"].s() : std::string("");
            std::string type = x.has("type") ? x["type"].s() : std::string("junction");
            double longitude = x["longitude"].d();
            double latitude = x["latitude"].d();
            int placeId = x.has("place_id") ? (int)x["place_id"].d() : 0;
            
            return mapService.createPathNode(name, type, longitude, latitude, placeId);
        } catch (const std::exception& e) {
            crow::json::wvalue error;
            error["error"] = std::string("创建节点失败: ") + e.what();
            return crow::response(500, error);
        }
    });
    
    // 路网编辑器API - 删除路径节点
    CROW_ROUTE(app, "/api/path_nodes/<int>")
    .methods("DELETE"_method)
    ([&mapService](int nodeId) {
        return mapService.deletePathNode(nodeId);
    });
    
    // 路网编辑器API - 获取所有路径
    CROW_ROUTE(app, "/api/paths")
    .methods("GET"_method)
    ([&mapService]() {
        return mapService.getAllPaths();
    });
    
    // 路网编辑器API - 创建路径
    CROW_ROUTE(app, "/api/paths")
    .methods("POST"_method)
    ([&mapService](const crow::request& req) {
        try {
            auto x = crow::json::load(req.body);
            if (!x) {
                crow::json::wvalue error;
                error["error"] = "无效的JSON数据";
                return crow::response(400, error);
            }
            
            std::string name = x.has("name") ? x["name"].s() : std::string("");
            int startNodeId = (int)x["start_node_id"].d();
            int endNodeId = (int)x["end_node_id"].d();
            double distance = x["distance"].d();
            int walkingTime = x.has("walking_time") ? (int)x["walking_time"].d() : 0;
            int ridingTime = x.has("riding_time") ? (int)x["riding_time"].d() : 0;
            int allowBike = x.has("allow_bike") ? (int)x["allow_bike"].d() : 1;
            double congestionBase = x.has("congestion_base") ? x["congestion_base"].d() : 0.7;
            int pathLevel = x.has("path_level") ? (int)x["path_level"].d() : 2;
            int bidirectional = x.has("bidirectional") ? (int)x["bidirectional"].d() : 1;
            
            return mapService.createPath(name, startNodeId, endNodeId, distance, 
                                       walkingTime, ridingTime, allowBike, 
                                       congestionBase, pathLevel, bidirectional);
        } catch (const std::exception& e) {
            crow::json::wvalue error;
            error["error"] = std::string("创建路径失败: ") + e.what();
            return crow::response(500, error);
        }
    });
    
    // 路网编辑器API - 删除路径
    CROW_ROUTE(app, "/api/paths/<int>")
    .methods("DELETE"_method)
    ([&mapService](int pathId) {
        return mapService.deletePath(pathId);
    });

    // 查找最近路网节点的API应该在setupRoutes方法中，而不是这里
}

// 实现代理API方法
crow::response MapService::proxyRouteApi(double startLat, double startLng, 
                                        double endLat, double endLng, 
                                        const std::string& mode, 
                                        const std::string& ak) {
    // 构建百度地图API URL - 使用Web API路线规划服务
    std::string url = "https://api.map.baidu.com/directionlite/v1/" + mode;
    url += "?origin=" + std::to_string(startLat) + "," + std::to_string(startLng);
    url += "&destination=" + std::to_string(endLat) + "," + std::to_string(endLng);
    url += "&ak=" + ak;
    
    // 初始化CURL
    CURL* curl = curl_easy_init();
    std::string responseString;
    
    if (curl) {
        // 设置URL
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        
        // 设置写回调函数
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &responseString);
        
        // 设置超时
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
        
        // 设置SSL验证
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
        
        // 执行请求
        CURLcode res = curl_easy_perform(curl);
        
        // 清理
        curl_easy_cleanup(curl);
        
        if (res != CURLE_OK) {
            std::cerr << "CURL错误: " << curl_easy_strerror(res) << std::endl;
            crow::json::wvalue error;
            error["status"] = 500;
            error["message"] = std::string("请求失败: ") + curl_easy_strerror(res);
            return crow::response(500, error);
        }
    } else {
        crow::json::wvalue error;
        error["status"] = 500;
        error["message"] = "CURL初始化失败";
        return crow::response(500, error);
    }
    
    // 解析JSON响应
    try {
        auto json = nlohmann::json::parse(responseString);
        
        // 转换为crow JSON格式并返回
        crow::json::wvalue result;
        
        // 显式转换JSON值以避免歧义
        if (json.contains("status")) {
            if (json["status"].is_number_integer()) {
                result["status"] = static_cast<int>(json["status"]);
            } else {
                result["status"] = json["status"].dump();
            }
        } else {
            result["status"] = 0;
        }
        
        if (json.contains("message")) {
            result["message"] = json["message"].get<std::string>();
        } else {
            result["message"] = "";
        }
        
        if (json.contains("result")) {
            // 这里可以根据需要转换result部分
            // 简化起见，直接返回原始响应
        }
        
        // 直接返回原始JSON响应
        crow::response response(responseString);
        response.set_header("Content-Type", "application/json");
        return response;
        
    } catch (const nlohmann::json::exception& e) {
        std::cerr << "JSON解析错误: " << e.what() << std::endl;
        crow::json::wvalue error;
        error["status"] = 500;
        error["message"] = std::string("JSON解析错误: ") + e.what();
        return crow::response(500, error);
    }
}

// 设置实例路由（包含需要访问实例成员的API）
void MapService::setupRoutes() {
    // 查找最近路网节点的API
    CROW_ROUTE(app_, "/api/find_nearest_node")
        .methods("GET"_method)
        ([this](const crow::request& req) {
            try {
                // 获取查询参数
                auto queryParams = req.url_params;
                double lng = 0.0, lat = 0.0;
                std::string name = "";
                
                try {
                    if (queryParams.get("lng")) {
                        lng = std::stod(queryParams.get("lng"));
                    }
                    if (queryParams.get("lat")) {
                        lat = std::stod(queryParams.get("lat"));
                    }
                    if (queryParams.get("name")) {
                        name = std::string(queryParams.get("name"));
                    }
                } catch (const std::exception& e) {
                    crow::json::wvalue response;
                    response["error"] = std::string("参数解析错误: ") + e.what();
                    return crow::response(response);
                }
                
                // 如果没有提供经纬度，但提供了名称，试图在数据库中查找
                if ((lng == 0.0 || lat == 0.0) && !name.empty()) {
                    // 使用新的方法查找地点关联的路网节点
                    int nodeId = this->findNodeByPlaceName(name);
                    
                    if (nodeId == -1) {
                        crow::json::wvalue response;
                        response["error"] = "根据名称无法找到节点";
                        return crow::response(response);
                    }
                    
                    // 获取节点详细信息
                    sqlite3* db;
                    if (sqlite3_open(dbPath_.c_str(), &db) != SQLITE_OK) {
                        crow::json::wvalue response;
                        response["error"] = "数据库连接失败";
                        return crow::response(response);
                    }
                    
                    std::string nodeSql = "SELECT name, longitude, latitude, type FROM path_nodes WHERE id = ?";
                    sqlite3_stmt* nodeStmt;
                    
                    if (sqlite3_prepare_v2(db, nodeSql.c_str(), -1, &nodeStmt, NULL) != SQLITE_OK) {
                        sqlite3_close(db);
                        crow::json::wvalue response;
                        response["error"] = "SQL准备失败";
                        return crow::response(response);
                    }
                    
                    sqlite3_bind_int(nodeStmt, 1, nodeId);
                    
                    crow::json::wvalue response;
                    if (sqlite3_step(nodeStmt) == SQLITE_ROW) {
                        response["id"] = nodeId;
                        response["name"] = sqlite3_column_text(nodeStmt, 0) ? 
                            std::string(reinterpret_cast<const char*>(sqlite3_column_text(nodeStmt, 0))) : name;
                        response["longitude"] = sqlite3_column_double(nodeStmt, 1);
                        response["latitude"] = sqlite3_column_double(nodeStmt, 2);
                        response["type"] = sqlite3_column_text(nodeStmt, 3) ? 
                            std::string(reinterpret_cast<const char*>(sqlite3_column_text(nodeStmt, 3))) : "junction";
                    } else {
                        response["error"] = "找不到节点数据";
                    }
                    
                    sqlite3_finalize(nodeStmt);
                    sqlite3_close(db);
                    
                    return crow::response(response);
                }
                
                // 否则，根据经纬度查找最近的节点
                int nodeId = this->findNearestNode(lng, lat);
                
                // 如果找不到节点，返回错误
                if (nodeId == -1) {
                    crow::json::wvalue response;
                    response["error"] = "找不到地图中的节点";
                    return crow::response(response);
                }
                
                // 获取节点信息
                sqlite3* db;
                if (sqlite3_open(dbPath_.c_str(), &db) != SQLITE_OK) {
                    crow::json::wvalue response;
                    response["error"] = "数据库连接失败";
                    return crow::response(response);
                }
                
                std::string nodeSql = "SELECT name, longitude, latitude, type FROM path_nodes WHERE id = ?";
                sqlite3_stmt* nodeStmt;
                
                if (sqlite3_prepare_v2(db, nodeSql.c_str(), -1, &nodeStmt, NULL) != SQLITE_OK) {
                    sqlite3_close(db);
                    crow::json::wvalue response;
                    response["error"] = "SQL准备失败";
                    return crow::response(response);
                }
                
                sqlite3_bind_int(nodeStmt, 1, nodeId);
                
                crow::json::wvalue response;
                if (sqlite3_step(nodeStmt) == SQLITE_ROW) {
                    response["id"] = nodeId;
                    response["name"] = sqlite3_column_text(nodeStmt, 0) ? 
                        std::string(reinterpret_cast<const char*>(sqlite3_column_text(nodeStmt, 0))) : 
                        (name.empty() ? "未命名节点" : name);
                    response["longitude"] = sqlite3_column_double(nodeStmt, 1);
                    response["latitude"] = sqlite3_column_double(nodeStmt, 2);
                    response["type"] = sqlite3_column_text(nodeStmt, 3) ? 
                        std::string(reinterpret_cast<const char*>(sqlite3_column_text(nodeStmt, 3))) : "junction";
                } else {
                    response["error"] = "找不到节点数据";
                }
                
                sqlite3_finalize(nodeStmt);
                sqlite3_close(db);
                
                return crow::response(response);
            } catch (const std::exception& e) {
                crow::json::wvalue response;
                response["error"] = std::string("查找节点时出错: ") + e.what();
                return crow::response(response);
            }
        });

    // 路线规划API
    CROW_ROUTE(app_, "/api/route_planning")
        .methods("POST"_method)
        ([this](const crow::request& req) {
            try {
                nlohmann::json requestData = nlohmann::json::parse(req.body);
                
                // 验证请求数据
                if (!requestData.contains("startPoint") || !requestData.contains("destinations")) {
                    crow::json::wvalue error;
                    error["success"] = false;
                    error["message"] = "缺少必要的起点或目的地信息";
                    return crow::response(400, error);
                }
                
                // 获取出行方式和规划策略
                bool isBiking = requestData.value("isBiking", false);
                bool isTimeOptimized = requestData.value("isTimeOptimized", false);
                
                auto startPoint = requestData["startPoint"];
                auto destinations = requestData["destinations"];
                
                crow::json::wvalue result;
                result["success"] = true;
                
                if (destinations.size() == 1) {
                    // 单目的地路线规划
                    auto singleDestResult = planSingleDestRoute(requestData);
                    
                    if (singleDestResult.contains("error")) {
                        result["success"] = false;
                        result["message"] = singleDestResult["error"].get<std::string>();
                        return crow::response(500, result);
                    }
                    
                    // 转换结果为crow::json格式
                    // 转换几何数据
                    crow::json::wvalue::list geometryList;
                    for (const auto& point : singleDestResult["path"]["geometry"]) {
                        crow::json::wvalue pointObj;
                        pointObj["lng"] = point["lng"].get<double>();
                        pointObj["lat"] = point["lat"].get<double>();
                        geometryList.push_back(std::move(pointObj));
                    }
                    result["path"]["geometry"] = std::move(geometryList);
                    result["path"]["distance"] = singleDestResult["path"]["distance"].get<double>();
                    result["path"]["time"] = singleDestResult["path"]["time"].get<double>();
                    
                    // 转换目的地数据
                    crow::json::wvalue::list destList;
                    for (const auto& dest : destinations) {
                        crow::json::wvalue destObj;
                        destObj["lng"] = dest["lng"].get<double>();
                        destObj["lat"] = dest["lat"].get<double>();
                        destObj["name"] = dest["name"].get<std::string>();
                        if (dest.contains("id")) {
                            destObj["id"] = dest["id"].get<int>();
                        }
                        destList.push_back(std::move(destObj));
                    }
                    result["destinations"] = std::move(destList);
                    
                    // 添加起点信息
                    result["startPoint"] = startPoint["name"].get<std::string>();
                    
                } else {
                    // 多目的地路线规划（TSP问题）
                    auto multiDestResult = planMultiDestRoute(requestData);
                    
                    if (multiDestResult.contains("error")) {
                        result["success"] = false;
                        result["message"] = multiDestResult["error"].get<std::string>();
                        return crow::response(500, result);
                    }
                    
                    // 转换路径段数据
                    crow::json::wvalue::list segmentsList;
                    for (const auto& segment : multiDestResult["path"]["pathSegments"]) {
                        crow::json::wvalue segmentObj;
                        
                        // 转换几何数据
                        crow::json::wvalue::list segmentGeometryList;
                        for (const auto& point : segment["geometry"]) {
                            crow::json::wvalue pointObj;
                            pointObj["lng"] = point["lng"].get<double>();
                            pointObj["lat"] = point["lat"].get<double>();
                            segmentGeometryList.push_back(std::move(pointObj));
                        }
                        segmentObj["geometry"] = std::move(segmentGeometryList);
                        segmentObj["distance"] = segment["distance"].get<double>();
                        segmentObj["time"] = segment["time"].get<double>();
                        
                        // 添加目的地名称信息
                        if (segment.contains("endName")) {
                            segmentObj["endName"] = segment["endName"].get<std::string>();
                        }
                        
                        segmentsList.push_back(std::move(segmentObj));
                    }
                    result["path"]["pathSegments"] = std::move(segmentsList);
                    result["path"]["totalDistance"] = multiDestResult["path"]["totalDistance"].get<double>();
                    result["path"]["totalTime"] = multiDestResult["path"]["totalTime"].get<double>();
                    
                    // 转换目的地数据
                    crow::json::wvalue::list destList;
                    for (const auto& dest : destinations) {
                        crow::json::wvalue destObj;
                        destObj["lng"] = dest["lng"].get<double>();
                        destObj["lat"] = dest["lat"].get<double>();
                        destObj["name"] = dest["name"].get<std::string>();
                        if (dest.contains("id")) {
                            destObj["id"] = dest["id"].get<int>();
                        }
                        destList.push_back(std::move(destObj));
                    }
                    result["destinations"] = std::move(destList);
                    
                    // 添加起点信息
                    result["startPoint"] = startPoint["name"].get<std::string>();
                }
                
                return crow::response(200, result);
                
            } catch (const nlohmann::json::exception& e) {
                crow::json::wvalue error;
                error["success"] = false;
                error["message"] = std::string("JSON解析错误: ") + e.what();
                return crow::response(400, error);
            } catch (const std::exception& e) {
                crow::json::wvalue error;
                error["success"] = false;
                error["message"] = std::string("路线规划错误: ") + e.what();
                return crow::response(500, error);
            }
        });
}

// findNearestNode函数的实现
int MapService::findNearestNode(double lng, double lat) {
    sqlite3* db;
    if (sqlite3_open(dbPath_.c_str(), &db) != SQLITE_OK) {
        std::cerr << "打开数据库失败: " << sqlite3_errmsg(db) << std::endl;
        return -1;
    }
    
    // 查找最近的节点，使用简单的欧几里得距离
    std::string sql = "SELECT id, longitude, latitude FROM path_nodes";
    sqlite3_stmt* stmt;
    
    if (sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, NULL) != SQLITE_OK) {
        std::cerr << "SQL准备失败: " << sqlite3_errmsg(db) << std::endl;
        sqlite3_close(db);
        return -1;
    }
    
    int nearestNodeId = -1;
    double minDistance = std::numeric_limits<double>::max();
    
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        int nodeId = sqlite3_column_int(stmt, 0);
        double nodeLng = sqlite3_column_double(stmt, 1);
        double nodeLat = sqlite3_column_double(stmt, 2);
        
        // 计算距离（简单的欧几里得距离）
        double dx = lng - nodeLng;
        double dy = lat - nodeLat;
        double distance = std::sqrt(dx * dx + dy * dy);
        
        if (distance < minDistance) {
            minDistance = distance;
            nearestNodeId = nodeId;
        }
    }
    
    sqlite3_finalize(stmt);
    sqlite3_close(db);
    
    return nearestNodeId;
}

// 新增：根据地点名称查找关联的路网节点
int MapService::findNodeByPlaceName(const std::string& placeName) {
    sqlite3* db;
    if (sqlite3_open(dbPath_.c_str(), &db) != SQLITE_OK) {
        std::cerr << "打开数据库失败: " << sqlite3_errmsg(db) << std::endl;
        return -1;
    }
    
    try {
        // 步骤1：从internal_places表中查找地点ID（北大内部地点）
        std::string placeSql = "SELECT id, longitude, latitude FROM internal_places WHERE name LIKE ?";
        sqlite3_stmt* placeStmt;
        
        if (sqlite3_prepare_v2(db, placeSql.c_str(), -1, &placeStmt, NULL) != SQLITE_OK) {
            sqlite3_close(db);
            return -1;
        }
        
        std::string namePattern = "%" + placeName + "%";
        sqlite3_bind_text(placeStmt, 1, namePattern.c_str(), -1, SQLITE_STATIC);
        
        int placeId = -1;
        double placeLng = 0.0, placeLat = 0.0;
        
        if (sqlite3_step(placeStmt) == SQLITE_ROW) {
            placeId = sqlite3_column_int(placeStmt, 0);
            placeLng = sqlite3_column_double(placeStmt, 1);
            placeLat = sqlite3_column_double(placeStmt, 2);
            std::cout << "在internal_places表中找到地点: " << placeName << ", ID=" << placeId << std::endl;
        }
        
        sqlite3_finalize(placeStmt);
        
        if (placeId == -1) {
            std::cout << "在internal_places表中找不到地点: " << placeName << std::endl;
            // 如果在internal_places中找不到，尝试直接按名称在path_nodes中查找
            std::string nodeNameSql = "SELECT id FROM path_nodes WHERE name LIKE ?";
            sqlite3_stmt* nodeNameStmt;
            
            if (sqlite3_prepare_v2(db, nodeNameSql.c_str(), -1, &nodeNameStmt, NULL) == SQLITE_OK) {
                sqlite3_bind_text(nodeNameStmt, 1, namePattern.c_str(), -1, SQLITE_STATIC);
                
                if (sqlite3_step(nodeNameStmt) == SQLITE_ROW) {
                    int nodeId = sqlite3_column_int(nodeNameStmt, 0);
                    std::cout << "在path_nodes表中按名称找到节点: " << placeName << ", 节点ID=" << nodeId << std::endl;
                    sqlite3_finalize(nodeNameStmt);
                    sqlite3_close(db);
                    return nodeId;
                }
                sqlite3_finalize(nodeNameStmt);
            }
            
            sqlite3_close(db);
            return -1;
        }
        
        // 步骤2：在path_nodes表中查找place_id等于该地点ID的节点
        std::string nodeSql = "SELECT id FROM path_nodes WHERE place_id = ?";
        sqlite3_stmt* nodeStmt;
        
        if (sqlite3_prepare_v2(db, nodeSql.c_str(), -1, &nodeStmt, NULL) != SQLITE_OK) {
            sqlite3_close(db);
            return -1;
        }
        
        sqlite3_bind_int(nodeStmt, 1, placeId);
        
        if (sqlite3_step(nodeStmt) == SQLITE_ROW) {
            int nodeId = sqlite3_column_int(nodeStmt, 0);
            std::cout << "找到关联的路网节点: 地点ID=" << placeId << ", 节点ID=" << nodeId << std::endl;
            sqlite3_finalize(nodeStmt);
            sqlite3_close(db);
            return nodeId;
        }
        
        sqlite3_finalize(nodeStmt);
        
        // 步骤3：如果没有关联的路网节点，查找最近的路网节点
        std::cout << "地点 " << placeName << " 没有关联的路网节点，查找最近的节点" << std::endl;
        int nearestNodeId = findNearestNode(placeLng, placeLat);
        
        sqlite3_close(db);
        return nearestNodeId;
        
    } catch (const std::exception& e) {
        std::cerr << "查找地点节点时出错: " << e.what() << std::endl;
        sqlite3_close(db);
        return -1;
    }
}

// 单目的地路线规划
nlohmann::json MapService::planSingleDestRoute(const nlohmann::json& requestData) {
    try {
        auto startPoint = requestData["startPoint"];
        auto destinations = requestData["destinations"];
        bool isBiking = requestData.value("isBiking", false);
        bool isTimeOptimized = requestData.value("isTimeOptimized", false);
        
        // 获取起点节点 - 先尝试按名称查找，再按坐标查找
        int startNodeId = -1;
        if (startPoint.contains("name") && !startPoint["name"].get<std::string>().empty()) {
            startNodeId = findNodeByPlaceName(startPoint["name"]);
        }
        if (startNodeId == -1) {
            startNodeId = findNearestNode(startPoint["lng"], startPoint["lat"]);
        }
        
        if (startNodeId == -1) {
            return nlohmann::json{{"error", "无法找到起点对应的路网节点"}};
        }
        
        // 获取目的地节点 - 先尝试按名称查找，再按坐标查找
        auto dest = destinations[0];
        int endNodeId = -1;
        if (dest.contains("name") && !dest["name"].get<std::string>().empty()) {
            endNodeId = findNodeByPlaceName(dest["name"]);
        }
        if (endNodeId == -1) {
            endNodeId = findNearestNode(dest["lng"], dest["lat"]);
        }
        
        if (endNodeId == -1) {
            return nlohmann::json{{"error", "无法找到目的地对应的路网节点"}};
        }
        
        std::cout << "路线规划: 起点节点ID=" << startNodeId << ", 目的地节点ID=" << endNodeId << std::endl;
        
        // 查找最短路径
        auto pathResult = findShortestPath(startNodeId, endNodeId, isBiking, isTimeOptimized);
        
        return pathResult;
        
    } catch (const std::exception& e) {
        return nlohmann::json{{"error", std::string("单目的地路线规划失败: ") + e.what()}};
    }
}

// 多目的地路线规划（TSP问题）
nlohmann::json MapService::planMultiDestRoute(const nlohmann::json& requestData) {
    try {
        auto startPoint = requestData["startPoint"];
        auto destinations = requestData["destinations"];
        bool isBiking = requestData.value("isBiking", false);
        bool isTimeOptimized = requestData.value("isTimeOptimized", false);
        
        // 获取起点节点
        int startNodeId = -1;
        if (startPoint.contains("name") && !startPoint["name"].get<std::string>().empty()) {
            startNodeId = findNodeByPlaceName(startPoint["name"]);
        }
        if (startNodeId == -1) {
            startNodeId = findNearestNode(startPoint["lng"], startPoint["lat"]);
        }
        
        if (startNodeId == -1) {
            return nlohmann::json{{"error", "无法找到起点对应的路网节点"}};
        }
        
        // 获取所有目的地节点
        std::vector<int> destNodeIds;
        for (const auto& dest : destinations) {
            int nodeId = -1;
            if (dest.contains("name") && !dest["name"].get<std::string>().empty()) {
                nodeId = findNodeByPlaceName(dest["name"]);
            }
            if (nodeId == -1) {
                nodeId = findNearestNode(dest["lng"], dest["lat"]);
            }
            
            if (nodeId == -1) {
                return nlohmann::json{{"error", "无法找到目的地对应的路网节点"}};
            }
            destNodeIds.push_back(nodeId);
        }
        
        // 构建距离矩阵
        std::vector<std::vector<double>> distanceMatrix;
        std::vector<int> allNodes = {startNodeId};
        allNodes.insert(allNodes.end(), destNodeIds.begin(), destNodeIds.end());
        
        int n = allNodes.size();
        distanceMatrix.resize(n, std::vector<double>(n, std::numeric_limits<double>::max()));
        
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (i == j) {
                    distanceMatrix[i][j] = 0.0;
                } else {
                    if (isTimeOptimized) {
                        distanceMatrix[i][j] = calculatePathTime(allNodes[i], allNodes[j], isBiking, true);
                    } else {
                        distanceMatrix[i][j] = calculatePathDistance(allNodes[i], allNodes[j]);
                    }
                }
            }
        }
        
        // 求解TSP问题
        auto tspOrder = solveTSP(distanceMatrix);
        
        // 构建完整路径
        nlohmann::json result;
        result["path"]["pathSegments"] = nlohmann::json::array();
        double totalDistance = 0.0;
        double totalTime = 0.0;
        
        for (size_t i = 0; i < tspOrder.size(); i++) {
            int currentNodeId = allNodes[tspOrder[i]];
            int nextNodeId = allNodes[tspOrder[(i + 1) % tspOrder.size()]];
            
            auto segmentPath = findShortestPath(currentNodeId, nextNodeId, isBiking, isTimeOptimized);
            if (segmentPath.contains("error")) {
                return nlohmann::json{{"error", "路径段规划失败"}};
            }
            
            // 添加目的地名称信息
            segmentPath["path"]["endName"] = "";
            int nextIndex = tspOrder[(i + 1) % tspOrder.size()];
            if (nextIndex > 0 && nextIndex <= (int)destinations.size()) {
                segmentPath["path"]["endName"] = destinations[nextIndex - 1]["name"].get<std::string>();
            } else if (nextIndex == 0) {
                segmentPath["path"]["endName"] = startPoint["name"].get<std::string>() + " (返回起点)";
            }
            
            result["path"]["pathSegments"].push_back(segmentPath["path"]);
            totalDistance += segmentPath["path"]["distance"];
            totalTime += segmentPath["path"]["time"];
        }
        
        result["path"]["totalDistance"] = totalDistance;
        result["path"]["totalTime"] = totalTime;
        
        return result;
        
    } catch (const std::exception& e) {
        return nlohmann::json{{"error", std::string("多目的地路线规划失败: ") + e.what()}};
    }
}

// 使用Dijkstra算法查找最短路径
nlohmann::json MapService::findShortestPath(int startNodeId, int endNodeId, bool isBiking, bool isTimeOptimized) {
    sqlite3* db;
    if (sqlite3_open(dbPath_.c_str(), &db) != SQLITE_OK) {
        return nlohmann::json{{"error", "数据库连接失败"}};
    }
    
    try {
        // 获取所有路径数据（包括拥挤度信息）
        std::string pathSql = "SELECT start_node_id, end_node_id, distance, allow_bike, congestion_base FROM paths";
        sqlite3_stmt* pathStmt;
        
        if (sqlite3_prepare_v2(db, pathSql.c_str(), -1, &pathStmt, NULL) != SQLITE_OK) {
            sqlite3_close(db);
            return nlohmann::json{{"error", "SQL准备失败"}};
        }
        
        // 构建图
        std::map<int, std::vector<std::pair<int, double>>> graph;
        
        while (sqlite3_step(pathStmt) == SQLITE_ROW) {
            int startNode = sqlite3_column_int(pathStmt, 0);
            int endNode = sqlite3_column_int(pathStmt, 1);
            double distance = sqlite3_column_double(pathStmt, 2);
            int allowBike = sqlite3_column_int(pathStmt, 3);
            double congestionBase = sqlite3_column_double(pathStmt, 4);
            
            // 骑行模式下的路径选择策略
            bool canUse = true;
            if (isBiking && !allowBike) {
                // 如果是骑行模式但路径不允许骑行，暂时跳过
                // 后续如果找不到完整的骑行路径，会降级到混合模式
                canUse = false;
            }
            
            double weight = distance; // 默认使用距离作为权重
            if (isTimeOptimized) {
                // 时间优化：考虑拥挤度的时间计算
                double actualCongestion = (congestionBase > 0.1) ? congestionBase : 0.8; // 使用数据库中的拥挤度
                double speed = (isBiking && allowBike) ? 15.0 : 5.0; // km/h，骑行15km/h，步行5km/h
                double actualSpeed = speed * actualCongestion; // 考虑拥挤度的实际速度
                weight = (distance / 1000.0) / actualSpeed * 60.0; // 转换为分钟
                
                std::cout << "路径 " << startNode << "->" << endNode 
                         << ": 距离=" << distance << "m, 拥挤度=" << actualCongestion 
                         << ", 权重(时间)=" << weight << "分钟" << std::endl;
            } else {
                // 距离优化：直接使用距离作为权重
                std::cout << "路径 " << startNode << "->" << endNode 
                         << ": 权重(距离)=" << weight << "米" << std::endl;
            }
            
            if (canUse || !isBiking) {
                graph[startNode].push_back({endNode, weight});
                graph[endNode].push_back({startNode, weight}); // 双向路径
            }
        }
        
        sqlite3_finalize(pathStmt);
        
        // 如果是骑行模式且无法找到路径，尝试混合模式（允许步行+骑行）
        bool needRetryWithMixedMode = false;
        
        // Dijkstra算法
        std::map<int, double> distances;
        std::map<int, int> previous;
        std::priority_queue<std::pair<double, int>, 
                           std::vector<std::pair<double, int>>, 
                           std::greater<std::pair<double, int>>> pq;
        
        distances[startNodeId] = 0.0;
        pq.push({0.0, startNodeId});
        
        while (!pq.empty()) {
            double currentDist = pq.top().first;
            int currentNode = pq.top().second;
            pq.pop();
            
            if (currentNode == endNodeId) {
                break;
            }
            
            if (currentDist > distances[currentNode]) {
                continue;
            }
            
            for (const auto& edge : graph[currentNode]) {
                int neighbor = edge.first;
                double weight = edge.second;
                double newDist = currentDist + weight;
                
                if (distances.find(neighbor) == distances.end() || newDist < distances[neighbor]) {
                    distances[neighbor] = newDist;
                    previous[neighbor] = currentNode;
                    pq.push({newDist, neighbor});
                }
            }
        }
        
        // 重构路径
        if (distances.find(endNodeId) == distances.end()) {
            if (isBiking) {
                // 骑行模式失败，尝试混合模式（包含所有路径）
                sqlite3_close(db);
                std::cout << "骑行路径不可达，尝试混合模式（步行+骑行）" << std::endl;
                return findShortestPath(startNodeId, endNodeId, false, isTimeOptimized);
            } else {
                sqlite3_close(db);
                return nlohmann::json{{"error", "无法找到有效路径"}};
            }
        }
        
        std::vector<int> pathNodes;
        int current = endNodeId;
        while (current != startNodeId) {
            pathNodes.push_back(current);
            current = previous[current];
        }
        pathNodes.push_back(startNodeId);
        std::reverse(pathNodes.begin(), pathNodes.end());
        
        // 获取路径几何数据
        nlohmann::json result;
        result["path"]["geometry"] = nlohmann::json::array();
        
        std::string nodeSql = "SELECT longitude, latitude FROM path_nodes WHERE id = ?";
        sqlite3_stmt* nodeStmt;
        sqlite3_prepare_v2(db, nodeSql.c_str(), -1, &nodeStmt, NULL);
        
        double totalDistance = 0.0;
        for (int nodeId : pathNodes) {
            sqlite3_bind_int(nodeStmt, 1, nodeId);
            if (sqlite3_step(nodeStmt) == SQLITE_ROW) {
                nlohmann::json point;
                point["lng"] = sqlite3_column_double(nodeStmt, 0);
                point["lat"] = sqlite3_column_double(nodeStmt, 1);
                result["path"]["geometry"].push_back(point);
            }
            sqlite3_reset(nodeStmt);
        }
        
        sqlite3_finalize(nodeStmt);
        sqlite3_close(db);
        
        // 分别计算实际距离和时间
        double actualDistance = 0.0;
        double actualTime = 0.0;
        
        // 计算路径的实际距离
        for (size_t i = 1; i < pathNodes.size(); i++) {
            int prevNodeId = pathNodes[i-1];
            int currentNodeId = pathNodes[i];
            
            // 查找这两个节点之间的实际路径距离
            sqlite3* tempDb;
            if (sqlite3_open(dbPath_.c_str(), &tempDb) == SQLITE_OK) {
                std::string pathDistSql = "SELECT distance FROM paths WHERE (start_node_id = ? AND end_node_id = ?) OR (start_node_id = ? AND end_node_id = ?)";
                sqlite3_stmt* pathDistStmt;
                if (sqlite3_prepare_v2(tempDb, pathDistSql.c_str(), -1, &pathDistStmt, NULL) == SQLITE_OK) {
                    sqlite3_bind_int(pathDistStmt, 1, prevNodeId);
                    sqlite3_bind_int(pathDistStmt, 2, currentNodeId);
                    sqlite3_bind_int(pathDistStmt, 3, currentNodeId);
                    sqlite3_bind_int(pathDistStmt, 4, prevNodeId);
                    
                    if (sqlite3_step(pathDistStmt) == SQLITE_ROW) {
                        double segmentDistance = sqlite3_column_double(pathDistStmt, 0);
                        actualDistance += segmentDistance;
                    }
                    sqlite3_finalize(pathDistStmt);
                }
                sqlite3_close(tempDb);
            }
        }
        
        // 根据出行方式计算实际时间
        double congestion = 0.8; // 默认拥挤度
        double speed = isBiking ? 15.0 : 5.0; // km/h，骑行15km/h，步行5km/h
        actualTime = (actualDistance / 1000.0) / (speed * congestion) * 60.0; // 转换为分钟
        
        result["path"]["distance"] = actualDistance; // 米
        result["path"]["time"] = actualTime; // 分钟
        
        std::cout << "路径计算完成: 距离=" << actualDistance << "米, 时间=" << actualTime << "分钟, 出行方式=" << (isBiking ? "骑行" : "步行") << std::endl;
        
        return result;
        
    } catch (const std::exception& e) {
        sqlite3_close(db);
        return nlohmann::json{{"error", std::string("路径查找失败: ") + e.what()}};
    }
}

// 计算两节点间的距离
double MapService::calculatePathDistance(int startNodeId, int endNodeId) {
    if (startNodeId == endNodeId) {
        return 0.0;
    }
    
    // 使用简化的Dijkstra算法计算最短距离
    auto pathResult = findShortestPath(startNodeId, endNodeId, false, false);
    
    if (pathResult.contains("error")) {
        // 如果无法找到路径，返回直线距离作为估算
        sqlite3* db;
        if (sqlite3_open(dbPath_.c_str(), &db) == SQLITE_OK) {
            std::string sql = "SELECT longitude, latitude FROM path_nodes WHERE id = ?";
            sqlite3_stmt* stmt;
            
            if (sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, NULL) == SQLITE_OK) {
                double startLng = 0, startLat = 0, endLng = 0, endLat = 0;
                
                // 获取起点坐标
                sqlite3_bind_int(stmt, 1, startNodeId);
                if (sqlite3_step(stmt) == SQLITE_ROW) {
                    startLng = sqlite3_column_double(stmt, 0);
                    startLat = sqlite3_column_double(stmt, 1);
                }
                sqlite3_reset(stmt);
                
                // 获取终点坐标
                sqlite3_bind_int(stmt, 1, endNodeId);
                if (sqlite3_step(stmt) == SQLITE_ROW) {
                    endLng = sqlite3_column_double(stmt, 0);
                    endLat = sqlite3_column_double(stmt, 1);
                }
                
                sqlite3_finalize(stmt);
                sqlite3_close(db);
                
                // 计算直线距离（经纬度转为米）
                double dx = (endLng - startLng) * 111320.0; // 1度经度约111320米
                double dy = (endLat - startLat) * 110540.0; // 1度纬度约110540米
                return std::sqrt(dx * dx + dy * dy);
            }
            sqlite3_close(db);
        }
        return 1000.0; // 默认距离
    }
    
    return pathResult["path"]["distance"].get<double>();
}

// 计算两节点间的时间
double MapService::calculatePathTime(int startNodeId, int endNodeId, bool isBiking, bool considerCongestion) {
    double distance = calculatePathDistance(startNodeId, endNodeId);
    double speed = isBiking ? 15.0 : 5.0; // km/h
    double congestion = considerCongestion ? 0.8 : 1.0;
    return (distance / 1000.0) / (speed * congestion) * 60.0; // 分钟
}

// 简化的TSP求解器（使用最近邻算法）
std::vector<int> MapService::solveTSP(const std::vector<std::vector<double>>& distanceMatrix) {
    int n = distanceMatrix.size();
    if (n <= 1) return {0};
    
    std::vector<int> tour;
    std::vector<bool> visited(n, false);
    
    int current = 0; // 从起点开始
    tour.push_back(current);
    visited[current] = true;
    
    for (int i = 1; i < n; i++) {
        int nearest = -1;
        double minDist = std::numeric_limits<double>::max();
        
        for (int j = 0; j < n; j++) {
            if (!visited[j] && distanceMatrix[current][j] < minDist) {
                minDist = distanceMatrix[current][j];
                nearest = j;
            }
        }
        
        if (nearest != -1) {
            tour.push_back(nearest);
            visited[nearest] = true;
            current = nearest;
        }
    }
    
    return tour;
}

// 路网编辑器API实现

// 获取所有路径节点
crow::response MapService::getAllPathNodes() {
    sqlite3* db;
    if (sqlite3_open(dbPath_.c_str(), &db) != SQLITE_OK) {
        crow::json::wvalue error;
        error["error"] = "数据库连接失败";
        return crow::response(500, error);
    }
    
    std::string sql = "SELECT id, name, type, longitude, latitude, place_id FROM path_nodes ORDER BY id";
    sqlite3_stmt* stmt;
    
    if (sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, NULL) != SQLITE_OK) {
        sqlite3_close(db);
        crow::json::wvalue error;
        error["error"] = "SQL准备失败";
        return crow::response(500, error);
    }
    
    crow::json::wvalue::list nodesList;
    
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        crow::json::wvalue node;
        node["id"] = sqlite3_column_int(stmt, 0);
        node["name"] = sqlite3_column_text(stmt, 1) ? 
            std::string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1))) : "";
        node["type"] = sqlite3_column_text(stmt, 2) ? 
            std::string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 2))) : "junction";
        node["longitude"] = sqlite3_column_double(stmt, 3);
        node["latitude"] = sqlite3_column_double(stmt, 4);
        node["place_id"] = sqlite3_column_int(stmt, 5);
        
        nodesList.push_back(std::move(node));
    }
    
    sqlite3_finalize(stmt);
    sqlite3_close(db);
    
    return crow::response(200, crow::json::wvalue(std::move(nodesList)));
}

// 获取所有路径
crow::response MapService::getAllPaths() {
    sqlite3* db;
    if (sqlite3_open(dbPath_.c_str(), &db) != SQLITE_OK) {
        crow::json::wvalue error;
        error["error"] = "数据库连接失败";
        return crow::response(500, error);
    }
    
    std::string sql = "SELECT p.id, p.name, p.start_node_id, p.end_node_id, p.distance, p.walking_time, "
                     "p.riding_time, p.allow_bike, p.congestion_base, p.path_level, p.bidirectional, "
                     "n1.longitude as start_lng, n1.latitude as start_lat, "
                     "n2.longitude as end_lng, n2.latitude as end_lat "
                     "FROM paths p "
                     "INNER JOIN path_nodes n1 ON p.start_node_id = n1.id "
                     "INNER JOIN path_nodes n2 ON p.end_node_id = n2.id "
                     "ORDER BY p.id";
    sqlite3_stmt* stmt;
    
    if (sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, NULL) != SQLITE_OK) {
        sqlite3_close(db);
        crow::json::wvalue error;
        error["error"] = "SQL准备失败";
        return crow::response(500, error);
    }
    
    crow::json::wvalue::list pathsList;
    
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        crow::json::wvalue path;
        path["id"] = sqlite3_column_int(stmt, 0);
        path["name"] = sqlite3_column_text(stmt, 1) ? 
            std::string(reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1))) : "";
        path["start_node_id"] = sqlite3_column_int(stmt, 2);
        path["end_node_id"] = sqlite3_column_int(stmt, 3);
        path["distance"] = sqlite3_column_double(stmt, 4);
        path["walking_time"] = sqlite3_column_int(stmt, 5);
        path["riding_time"] = sqlite3_column_int(stmt, 6);
        path["allow_bike"] = sqlite3_column_int(stmt, 7);
        path["congestion_base"] = sqlite3_column_double(stmt, 8);
        path["path_level"] = sqlite3_column_int(stmt, 9);
        path["bidirectional"] = sqlite3_column_int(stmt, 10);
        path["start_lng"] = sqlite3_column_double(stmt, 11);
        path["start_lat"] = sqlite3_column_double(stmt, 12);
        path["end_lng"] = sqlite3_column_double(stmt, 13);
        path["end_lat"] = sqlite3_column_double(stmt, 14);
        
        pathsList.push_back(std::move(path));
    }
    
    sqlite3_finalize(stmt);
    sqlite3_close(db);
    
    return crow::response(200, crow::json::wvalue(std::move(pathsList)));
}

// 创建路径节点
crow::response MapService::createPathNode(const std::string& name, const std::string& type, 
                                        double longitude, double latitude, int placeId) {
    sqlite3* db;
    if (sqlite3_open(dbPath_.c_str(), &db) != SQLITE_OK) {
        crow::json::wvalue error;
        error["error"] = "数据库连接失败";
        return crow::response(500, error);
    }
    
    std::string sql = "INSERT INTO path_nodes (name, type, longitude, latitude, place_id) "
                     "VALUES (?, ?, ?, ?, ?)";
    sqlite3_stmt* stmt;
    
    if (sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, NULL) != SQLITE_OK) {
        sqlite3_close(db);
        crow::json::wvalue error;
        error["error"] = "SQL准备失败";
        return crow::response(500, error);
    }
    
    sqlite3_bind_text(stmt, 1, name.c_str(), -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 2, type.c_str(), -1, SQLITE_STATIC);
    sqlite3_bind_double(stmt, 3, longitude);
    sqlite3_bind_double(stmt, 4, latitude);
    sqlite3_bind_int(stmt, 5, placeId);
    
    int result = sqlite3_step(stmt);
    sqlite3_finalize(stmt);
    
    if (result == SQLITE_DONE) {
        int nodeId = static_cast<int>(sqlite3_last_insert_rowid(db));
        sqlite3_close(db);
        
        crow::json::wvalue response;
        response["id"] = nodeId;
        response["message"] = "节点创建成功";
        return crow::response(200, response);
    } else {
        sqlite3_close(db);
        crow::json::wvalue error;
        error["error"] = "节点创建失败";
        return crow::response(500, error);
    }
}

// 创建路径
crow::response MapService::createPath(const std::string& name, int startNodeId, int endNodeId, 
                                    double distance, int walkingTime, int ridingTime, 
                                    int allowBike, double congestionBase, int pathLevel, int bidirectional) {
    sqlite3* db;
    if (sqlite3_open(dbPath_.c_str(), &db) != SQLITE_OK) {
        crow::json::wvalue error;
        error["error"] = "数据库连接失败";
        return crow::response(500, error);
    }
    
    std::string sql = "INSERT INTO paths (name, start_node_id, end_node_id, distance, walking_time, "
                     "riding_time, allow_bike, congestion_base, path_level, bidirectional) "
                     "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    sqlite3_stmt* stmt;
    
    if (sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, NULL) != SQLITE_OK) {
        sqlite3_close(db);
        crow::json::wvalue error;
        error["error"] = "SQL准备失败";
        return crow::response(500, error);
    }
    
    sqlite3_bind_text(stmt, 1, name.c_str(), -1, SQLITE_STATIC);
    sqlite3_bind_int(stmt, 2, startNodeId);
    sqlite3_bind_int(stmt, 3, endNodeId);
    sqlite3_bind_double(stmt, 4, distance);
    sqlite3_bind_int(stmt, 5, walkingTime);
    sqlite3_bind_int(stmt, 6, ridingTime);
    sqlite3_bind_int(stmt, 7, allowBike);
    sqlite3_bind_double(stmt, 8, congestionBase);
    sqlite3_bind_int(stmt, 9, pathLevel);
    sqlite3_bind_int(stmt, 10, bidirectional);
    
    int result = sqlite3_step(stmt);
    sqlite3_finalize(stmt);
    
    if (result == SQLITE_DONE) {
        int pathId = static_cast<int>(sqlite3_last_insert_rowid(db));
        sqlite3_close(db);
        
        crow::json::wvalue response;
        response["id"] = pathId;
        response["message"] = "路径创建成功";
        return crow::response(200, response);
    } else {
        sqlite3_close(db);
        crow::json::wvalue error;
        error["error"] = "路径创建失败";
        return crow::response(500, error);
    }
}

// 删除路径节点
crow::response MapService::deletePathNode(int nodeId) {
    sqlite3* db;
    if (sqlite3_open(dbPath_.c_str(), &db) != SQLITE_OK) {
        crow::json::wvalue error;
        error["error"] = "数据库连接失败";
        return crow::response(500, error);
    }
    
    // 检查节点是否被路径使用
    std::string checkSql = "SELECT COUNT(*) FROM paths WHERE start_node_id = ? OR end_node_id = ?";
    sqlite3_stmt* checkStmt;
    
    if (sqlite3_prepare_v2(db, checkSql.c_str(), -1, &checkStmt, NULL) != SQLITE_OK) {
        sqlite3_close(db);
        crow::json::wvalue error;
        error["error"] = "SQL准备失败";
        return crow::response(500, error);
    }
    
    sqlite3_bind_int(checkStmt, 1, nodeId);
    sqlite3_bind_int(checkStmt, 2, nodeId);
    
    int count = 0;
    if (sqlite3_step(checkStmt) == SQLITE_ROW) {
        count = sqlite3_column_int(checkStmt, 0);
    }
    sqlite3_finalize(checkStmt);
    
    if (count > 0) {
        sqlite3_close(db);
        crow::json::wvalue error;
        error["message"] = "无法删除节点，因为它被路径使用";
        return crow::response(400, error);
    }
    
    // 删除节点
    std::string deleteSql = "DELETE FROM path_nodes WHERE id = ?";
    sqlite3_stmt* deleteStmt;
    
    if (sqlite3_prepare_v2(db, deleteSql.c_str(), -1, &deleteStmt, NULL) != SQLITE_OK) {
        sqlite3_close(db);
        crow::json::wvalue error;
        error["error"] = "SQL准备失败";
        return crow::response(500, error);
    }
    
    sqlite3_bind_int(deleteStmt, 1, nodeId);
    
    int result = sqlite3_step(deleteStmt);
    sqlite3_finalize(deleteStmt);
    sqlite3_close(db);
    
    if (result == SQLITE_DONE) {
        crow::json::wvalue response;
        response["message"] = "节点删除成功";
        return crow::response(200, response);
    } else {
        crow::json::wvalue error;
        error["message"] = "节点删除失败";
        return crow::response(500, error);
    }
}

// 删除路径
crow::response MapService::deletePath(int pathId) {
    sqlite3* db;
    if (sqlite3_open(dbPath_.c_str(), &db) != SQLITE_OK) {
        crow::json::wvalue error;
        error["error"] = "数据库连接失败";
        return crow::response(500, error);
    }
    
    std::string sql = "DELETE FROM paths WHERE id = ?";
    sqlite3_stmt* stmt;
    
    if (sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, NULL) != SQLITE_OK) {
        sqlite3_close(db);
        crow::json::wvalue error;
        error["error"] = "SQL准备失败";
        return crow::response(500, error);
    }
    
    sqlite3_bind_int(stmt, 1, pathId);
    
    int result = sqlite3_step(stmt);
    sqlite3_finalize(stmt);
    sqlite3_close(db);
    
    if (result == SQLITE_DONE) {
        crow::json::wvalue response;
        response["message"] = "路径删除成功";
        return crow::response(200, response);
    } else {
        crow::json::wvalue error;
        error["message"] = "路径删除失败";
        return crow::response(500, error);
    }
} 

// API密钥轮换方法实现
void MapService::rotateServerAk() {
    // 轮换到下一个密钥
    currentServerAkIndex = (currentServerAkIndex + 1) % serverAks.size();
    ak = serverAks[currentServerAkIndex];
    
    std::cout << "轮换API密钥，当前使用索引: " << currentServerAkIndex 
              << ", 密钥: " << ak.substr(0, 8) << "..." << std::endl;
}

// 支持密钥轮换的路线规划API调用
crow::response MapService::proxyRouteApiWithRetry(double startLat, double startLng, 
                                                 double endLat, double endLng, 
                                                 const std::string& mode) {
    int maxRetries = serverAks.size();  // 最多重试所有密钥一遍
    
    for (int attempt = 0; attempt < maxRetries; attempt++) {
        std::cout << "路线规划API调用，尝试 " << (attempt + 1) << "/" << maxRetries 
                  << "，使用密钥索引: " << currentServerAkIndex << std::endl;
        
        // 调用静态方法
        crow::response response = proxyRouteApi(startLat, startLng, endLat, endLng, mode, ak);
        
        // 检查响应状态
        if (response.code == 200) {
            try {
                // 解析响应，检查百度API状态
                auto json = nlohmann::json::parse(response.body);
                if (json.contains("status")) {
                    int status = json["status"].get<int>();
                    if (status == 0) {
                        // 成功
                        std::cout << "路线规划成功，使用密钥索引: " << currentServerAkIndex << std::endl;
                        return response;
                    } else if (status == 240) {
                        // APP服务被禁用，轮换密钥重试
                        std::cout << "密钥 " << currentServerAkIndex << " 服务被禁用（状态码240），轮换密钥重试" << std::endl;
                        rotateServerAk();
                        continue;
                    } else if (status == 4) {
                        // 配额超限，轮换密钥重试
                        std::cout << "密钥 " << currentServerAkIndex << " 配额超限（状态码4），轮换密钥重试" << std::endl;
                        rotateServerAk();
                        continue;
                    } else {
                        // 其他错误，直接返回
                        std::cout << "路线规划API返回错误状态: " << status << std::endl;
                        return response;
                    }
                }
            } catch (const std::exception& e) {
                std::cout << "解析响应时出错: " << e.what() << std::endl;
                return response;
            }
        } else {
            // HTTP请求失败，尝试下一个密钥
            std::cout << "HTTP请求失败，状态码: " << response.code << "，轮换密钥重试" << std::endl;
            rotateServerAk();
        }
    }
    
    // 所有密钥都尝试失败
    crow::json::wvalue error;
    error["status"] = 500;
    error["message"] = "所有API密钥都无法使用，请检查密钥配置或联系管理员";
    return crow::response(500, error);
}